//
//  WBNetworkManager.swift
//  SwiftWeibo
//
//  Created by Lausen on 2017/4/15.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod{
    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {

    /// 网络工具对象的单例
    static let shared: WBNetworkManager = {
        
        //实例化一个网络管理对象
        let instance = WBNetworkManager()
        
        //设置反序列化可接受的类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //返回一个网络管理的实例对象
        return instance
    }()
    
    lazy var userAccount = WBUserAccount()
    
    /// 计算性属性.判断token是否为空来判断用户是否登录了
    var userLogon: Bool{
        
        return (userAccount.access_token != nil)
        
    }
    
    
    /// 上传文件的方法
    ///
    /// - Parameters:
    ///   - urlString: 上传至服务器的连接
    ///   - param: 上传需要的参数
    ///   - name: 接受上传数据的服务器字段(要咨询公司的后台)
    ///   - data: 要上传的二进制数据
    ///   - completion: 完成上传的回调
    func loadup(urlString: String,param: [String: Any]?,name: String,data: Data,completion:@escaping(_ result: Any?,_ isSuccess: Bool) -> ()) -> Void {
        
        post(urlString, parameters: param, constructingBodyWith: { (formData) in
            
            //FIXME: -- 创建formData
            /**
             fileData: 要上传的二进制数据
             name:     服务器接受数据的字段名
             fileName: 保存在服务器上的文件名 (大多数服务器可以乱写)
             mimeType: 告诉服务器上传的文件类型,如果不想告诉,可以写"application/octet-stream"
                        image/png image/jpg image/gif
             */
            formData.appendPart(withFileData: data, name: name, fileName: "xxx", mimeType: "application/octex-stream")
            
        }, progress: nil, success: { (task, result) in
            
            completion(result, true)
            
        }) { (task, error) in
            
            if((task?.response as? HTTPURLResponse)?.statusCode == 403){
                
                print("token过期了.请重新登录")
                
                //发送通知,谁接受到通知,谁做处理,处理重新登录,如果是token过期了,就需要让其重新登录了,这个时候,就要提示和延时
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLogonNotification), object: "lausen")
            }
        }
    }
    
    ///因为token是除了登录之外所有的接口都要用到的一个参数,所以封装起来,不用每次都传这个参数了
    func tokenRequest(WBHTTPMethod:WBHTTPMethod = .GET,URLString:String,parameters:[String:Any]?,completion:@escaping (_ json:Any?,_ isSecuess:Bool)->()) {
        
        guard let token = userAccount.access_token else {
            
            //发送通知,谁接受到通知,谁做处理
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLogonNotification), object: nil)
            
            ///调用一下错误的闭包
            completion(nil, false)
            
            print("没有token,请重新登录")
            
            return
        }
        
        var parameters = parameters
        if parameters == nil {
            
            parameters = [String:Any]()
        }
        
        parameters!["access_token"] = token
        
        //调用request
        request(WBHTTPMethod: WBHTTPMethod, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    func request (WBHTTPMethod:WBHTTPMethod = .GET,URLString:String,parameters:[String:Any]?,completion:@escaping (_ json:Any?,_ isSecuess:Bool)->()) -> () {
        
        let success = {(task:URLSessionDataTask , json:Any?) -> () in
            
            completion(json, true)
        }
        
        let failure = {(task:URLSessionDataTask?,error:Error) -> () in
            
            if((task?.response as? HTTPURLResponse)?.statusCode == 403){
                
                print("token过期了.请重新登录")
                
                //发送通知,谁接受到通知,谁做处理,处理重新登录,如果是token过期了,就需要让其重新登录了,这个时候,就要提示和延时
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLogonNotification), object: "lausen")
            }
            
            print("网络错误\(error)")
            
            completion(error, false)
        }
        
        
        if WBHTTPMethod == .GET { //如果是get请求
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }else{ //如果是post请求
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
